package dai.samples.mongodb.service.impl;

import dai.samples.mongodb.entity.Product;
import dai.samples.mongodb.repository.ProductRepository;
import dai.samples.mongodb.repository.UserInfoRepository;
import dai.samples.mongodb.service.EasyCRUDService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 使用MongoRepository做CRUD的相关例子
 */
@Service
public class EasyCRUDServiceImpl implements EasyCRUDService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserInfoRepository infoRepository;

    @Override
    public void saveOne(Product product) {
        productRepository.save(product);
    }

    @Override
    public void batchSave(List<Product> products) {
        productRepository.saveAll(products);
    }

    @Override
    public void updateOne(Product product) {
        productRepository.save(product);
    }

    @Override
    public void batchUpdate(List<Product> products) {
        productRepository.saveAll(products);
    }

    @Override
    public Product queryById(String id) {
        return productRepository.findById(id).get();
    }

    @Override
    public List<Product> queryByEntity(Product product) {

        Example<Product> of = Example.of(product);

        List<Product> all = productRepository.findAll(of);
        return all;
    }

    @Override
    public Page<Product> pageByEntity(Product product, int page, int size) {
        Example<Product> of = Example.of(product);
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> all = productRepository.findAll(of, pageable);

        return all;
    }

    @Override
    public void deleteOne(String id) {
        productRepository.deleteById(id);
    }

    @Override
    public void batchDelete(List<String> idList) {
        productRepository.deleteAllByIdIn(idList);
    }
}
